import { message } from "antd";
import { EXCLUDE } from "../utils/token";
import axios from "axios";
export const http = axios.create({
  baseURL: "/api",
  timeout: 2000,
});
// 拦截器
http.interceptors.request.use(
  (config: any) => {
    const token = localStorage.getItem("token");
    console.log(token);
    console.log(EXCLUDE.includes(config.url));
    if (!EXCLUDE.includes(config.url)) {
      if (!token) {
        // 如果 token 过期，重定向到登录页面
        window.location.href = "/";
        return Promise.reject("Token expired");
      }
    }

    config.headers.Authorization = token;
    config.withCredentials = true;
    return config;
  },
  (err: any) => {
    return Promise.reject(err);
  }
);

http.interceptors.response.use(
  (res: any) => {
    if (res.data.code !== 200&&res.data.code !== 414) {
      message.info(res.data.msg);
      return Promise.reject(res.data.msg);
    }
    if (res.config.url === "/user/login") {
      return res.data;
    }
    return res.data.data;
  },
  (err: any) => {
    if (err.response) {
      switch (err.response.status) {
        case 401:
          // 401 未登录
          message.error("未登录");
          localStorage.removeItem("token");
          window.location.href = "/";
          break;
        case 403:
          // 403 无权限
          message.error("无权限");
          break;
        case 404:
          // window.location.href = "/notfound";
          break;
        case 500:
          message.error("服务器内部错误");
          break;
      }
    }
    return Promise.reject(err);
  }
);
